package com.kuangstudy.controller;

import com.kuangstudy.anno.AccessIpLimiter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月14日 21:03:00
 * @Description
 */

@RestController
@Slf4j
@Api(tags = "用户redis操作")
public class UserLuaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DefaultRedisScript<Long> userLuaScript;


    @PostMapping("/user/lua/update")
    @ApiOperation("利用lua脚本更新redis中用户信息")
    @AccessIpLimiter(timeout = 20,limit = 3,key = "user:limit")
    public Long luaToUpdateUser(@RequestParam("userId") Long userId, @RequestParam("nickName")String nickName){
        String key = "user:" + userId;
        // 1、设置lua的key
        List<String> keysList = Arrays.asList(key);
        Long result = stringRedisTemplate.execute(userLuaScript, keysList, nickName);
        return result;
    }


    @PostMapping("/user/update")
    @ApiOperation("利用java代码更新redis中用户信息")
    public Long updateUser(Long userId,String nickname){
        String key = "user:" + userId;
        // 1、在缓存中找到这个key是否存在
        String oldUser = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isNotBlank(oldUser)){
            // 2、如果不存在，直接新增
            stringRedisTemplate.opsForValue().set(key,nickname);
            return 1L;
        }

        // 说明key存在，那么要判断设置的值和redis存放的值是否一致，一致不做任何操作
        if (nickname.equals(oldUser)){
            log.info("用户对象:{}，无须修改!", key);
        }else {
            log.info("用户对象:{}，修改成功!", key);
            // 直接修改redis中的值
            stringRedisTemplate.opsForValue().set(key,nickname);
            return 1L;
        }
        return 0L;
    }

}
